package org.atlantis.evnlib.execution;

import java.util.Collection;

import org.atlantis.evnlib.EventArg;
import org.atlantis.evnlib.EventProxy;
import org.atlantis.evnlib.EventReceiver;
import org.atlantis.evnlib.execution.rejecter.RejectedTaskHandler;
import org.atlantis.evnlib.task.TaskExecutor;

/***
 * 任务池事件执行器适配器。使用任务池来执行事件监听器。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">李曦</a><br/>
 *         Created at: 2011-7-4 上午10:15:13
 */
public class TaskEventExecutor implements EventExecutor {

	private TaskExecutor executor;

	public TaskEventExecutor(RejectedTaskHandler rejectedTaskHandler) {
		this.executor = new TaskExecutor(rejectedTaskHandler);
	}

	@Override
	public void addEvent(EventProxy ep) {
		executor.createTaskPool(ep.getEventName(), ep.getFixedThreadSize(), ep.getFlexThreadSize(), ep.getQueueSize());
	}

	@Override
	public Collection<Runnable> removeEvent(EventProxy ep) {
		return executor.destoryTaskPool(ep.getEventName());
	}

	@Override
	public void execute(final EventReceiver eventReceiver, final EventArg eventArg) {
		executor.submit(eventArg.getEventName(), new Runnable() {
			@Override
			public void run() {
				eventReceiver.receive(eventArg);
			}
		});
	}

	@Override
	public Collection<Runnable> shutdownNow() {
		return executor.shutdownNow();
	}
}
